import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/HomeView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/course/:id',
    name: 'CourseDetail',
    component: () => import('../views/CourseDetailView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/add-course',
    name: 'AddCourse',
    component: () => import('../views/AddCourseView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/add-category',
    name: 'AddCategory',
    component: () => import('../views/AddCategoryView.vue'),
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  // 使用 Hash 模式确保在各种部署环境下都能正常工作
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next('/login')
  } else {
    next()
  }
})

export default router